package com.lkd.handler;


import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
@Slf4j
public class VMStatusHandler implements MsgHandler {

    @Autowired
    private VMService vmService;
    @Autowired
    private TaskService taskService;


    @Override
    public void process(String jsonMsg) throws IOException {
        //消息装换对象
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        //判断对象是否为空
        if (vmStatusContract==null ||vmStatusContract.getStatusInfo()==null||vmStatusContract.getStatusInfo().size()<=0)
            return;
        //消息中由不正常的状态，需要创建维修工单
        if (vmStatusContract.getStatusInfo().stream().anyMatch(s->s.isStatus()==false)){
            //根据售货机编号查询售货机
            try {
                VmVO vmInfo = vmService.getVMInfo(vmStatusContract.getInnerCode());
                if (vmInfo==null){
                    return;
                }
                //查询工单量最少的用户
                Integer userId = taskService.getLeastUser(vmInfo.getRegionId(), true);
                //创建维修自动维修工单
                TaskViewModel taskViewModel = new TaskViewModel();
                taskViewModel.setAssignorId(0);
                taskViewModel.setDesc(jsonMsg);
                taskViewModel.setInnerCode(vmStatusContract.getInnerCode());
                taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);//维修工单
                taskViewModel.setUserId(userId);
                taskService.createTask(taskViewModel);
            } catch (Exception e) {
                log.error("自动创建维修工单失败");
            }


        }
    }
}
